package com.czp.user.service.impl;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.RowBounds;

import com.czp.framework.model.DataStoreTemplate;
import com.czp.framework.util.DateUtils;
import com.czp.framework.util.HttpUtils;
import com.czp.framework.util.JsonUtils;
import com.czp.log.model.Log;
import com.czp.user.mapper.IUserMapper;
import com.czp.user.model.RelationRole;
import com.czp.user.model.User;
import com.czp.user.service.IUserService;
import com.google.gson.Gson;

/**
 * 【环 境】：J2SE 1.7
 * @author   柴志鹏	CHAIZP@GMAIL.COM
 * @version  version 1.0
 * @since    2014-4-25
 */
public class UserServiceImpl implements IUserService {
	private IUserMapper userMapper;
	private Gson gson = new Gson();
	
	public int userController(User user) throws Exception {
		user.setModifyDate(DateUtils.getSysTimestamp());
		if(user.getCudType().equals("C")) {//创建
			user.setCreateDate(DateUtils.getSysTimestamp());
			return userMapper.addUser(user);
		} else if(user.getCudType().equals("U") && !user.getId().equals("")) {
			return userMapper.editorUser(user);
		} else if(user.getCudType().equals("D") && !user.getId().equals("")) {
			return userMapper.deleteUser(user);
		}
		return 0;
	}
	
	public String getUserInfoByPid(String personId) throws Exception {
		User user = userMapper.getUserInfoByPid(personId);
		return gson.toJson(user);
	}
	
	public String queryRelationRole(String personId) throws Exception {
		return gson.toJson(
				userMapper.queryRelationRole(personId));
	}
	
	public String getSelectedRoleList(RelationRole relRole) throws Exception {
		DataStoreTemplate dst = new DataStoreTemplate();
		dst.setList(userMapper.getSelectedRoleList(relRole, new RowBounds(relRole.getStart(), relRole.getLimit())));
		dst.setTotal(userMapper.getSelectedRoleRecords(relRole));
		return gson.toJson(dst);
	}
	
	public int relationRoleController(String jsonData) throws Exception {
		JSONArray jsonArr = JSONArray.fromObject(jsonData);
		if(jsonArr == null || jsonArr.isEmpty()) {
			return 0;
		}
		RelationRole relRole = new RelationRole();
		int i = 0;
		for(int cnt = jsonArr.size(); i < cnt; i++) {
			JSONObject jsonObj = jsonArr.getJSONObject(i);
			JsonUtils.jsonToBean(jsonObj, relRole);
			if(relRole.getChecked().equals("true")) {
				// 当管理角色不存在时才添加新数据，防止违反唯一约束
				if(userMapper.matchAddRelationRole(relRole) == 0) {
					userMapper.insertRelationRole(relRole);
				}
			} else {
				userMapper.deleteRelationRole(relRole);
			}
		}
		return i;
	}
	
	public int deleteRelationRole(String jsonData) throws Exception {
		JSONArray jsonArr = JSONArray.fromObject(jsonData);
		if(jsonArr == null || jsonArr.isEmpty()) {
			return 0;
		}
		RelationRole relRole = new RelationRole();
		int i = 0;
		for(int cnt = jsonArr.size(); i < cnt; i++) {
			JSONObject jsonObj = jsonArr.getJSONObject(i);
			JsonUtils.jsonToBean(jsonObj, relRole);
			userMapper.deleteRelationRole(relRole);
		}
		return i;
	}
	
	public String queryRelationMenu(String personId) throws Exception {
		return gson.toJson(
				userMapper.queryRelationMenu(personId));
	}
	
	public User login(String username) throws Exception {
		return userMapper.login(username);
	}
	
	public int isUserExist(String username) throws Exception {
		return userMapper.isUserExist(username);
	}
	
	public int modifyPassword(User user) throws Exception {
		String password = userMapper.queryPasswordById(user.getId());
		if(password != null && password.equals(user.getOldPass())) {
			userMapper.modifyPassword(user);
			return 1;//成功
		}
		return 0;//失败
	}
	
	public int addLoginLogInfo(String username, 
			String password, String ip, String status) throws Exception {
		Log log = new Log();
		log.setUsername(username);
		log.setName((String) HttpUtils.getSession("name"));
		log.setLoginTime(DateUtils.getSysTimestamp());
		log.setIp(ip);
		if(status.equals("0")) {
			log.setStatus("0|登录成功");
		} else if(status.equals("1")) {
			log.setStatus("1|密码错误：尝试登录密码为" + password);
		} else if(status.equals("2")) {
			log.setStatus("2|登录用户已被禁用");
		} else if(status.equals("3")) {
			log.setStatus("3|登录失败：用户不存在，尝试用户" + username);
		}
		return userMapper.addLoginLogInfo(log);
	}
	
	/**
	 * 获取 userMapper
	 * @return 返回 userMapper
	 */
	public IUserMapper getUserMapper() {
		return userMapper;
	}

	/**
	 * 设置 userMapper
	 * @param 对userMapper进行赋值
	 */
	public void setUserMapper(IUserMapper userMapper) {
		this.userMapper = userMapper;
	}
	
}
